package com.example.interceptor.common;

import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.example.interceptor.utils.jwt.JWTUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class JwtInterceptor implements HandlerInterceptor {

    private static final String AUTH_HEADER = "Authorization";
    private static final String TOKEN_PREFIX = "Bearer ";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("add jwt...");
        // 从请求头中获取Authorization字段
        String token = request.getHeader(AUTH_HEADER);
        System.out.println(token);

        // 检查Authorization头是否存在并且以Bearer开头
        if (token != null && token.startsWith(TOKEN_PREFIX)) {
            try {
                // 去除Bearer前缀，获取实际token字符串
                String jwtToken = token.replace(TOKEN_PREFIX, "").trim();

                System.out.println(jwtToken);
                // 使用您的JWT工具类解析token
                DecodedJWT decodedJWT = JWTUtils.decode(jwtToken);
                // 获取解析后的token中的payload信息
                String name = decodedJWT.getClaim("admin").asString();
                System.out.println(name);
                System.out.println(decodedJWT.getClaim("shenfen").asString());
                return true; // 继续处理请求
            } catch (Exception e) {
                // JWT验证失败，返回错误响应
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                response.getWriter().write("Unauthorized-failed");
                return false; // 停止处理请求
            }
        } else {
            // 请求中没有Authorization头，返回错误响应
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("Unauthorized-none");
            return false; // 停止处理请求
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // 可在请求处理后进行一些处理，如果不需要可以不实现此方法
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 请求处理完成后的清理工作，如果不需要可以不实现此方法
    }
}
